﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;



#region 配置文件

public class ConfigDic
{

    public static string configFileName;
    public static Dictionary<string, string> ConfigTable = new Dictionary<string, string>(); 

    public static void getConfigTable()
    {
        try
        {
            Int32 i;
            string[] arrS = FileOperate.ReadFile(configFileName).Split('\n');
            ConfigTable.Clear();
            for (i = 0; i < arrS.Length; i++)
            {
                try
                {
                    arrS[i] = arrS[i].Replace("\r", "").Trim();
                    if (arrS[i].Length > 0)
                    {
                        string[] arrS2 = arrS[i].Split('=');
                        if ((arrS2.Length >= 2))
                        {
                            string key = arrS2[0];
                            string truevalue = "";
                            for (Int32 j = 1; j < arrS2.Length; j++)
                            {
                                truevalue += arrS2[j];
                                if (j < arrS2.Length - 1)
                                {
                                    truevalue += "=";
                                }
                            }
                            ConfigTable.Add(key, truevalue);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Record(ex);
                }
            }
        }
        catch (Exception ex)
        {
            Log.Record(ex);
        }
    }

    public static void saveConfigTable()
    {
        try
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder(400);

            foreach (KeyValuePair<string, string> item in ConfigTable)
            {
                sb.Append(item.Key);
                sb.Append("=");
                sb.Append(item.Value);
                sb.Append("\r\n");
            }


            FileOperate.WriteFile(configFileName, sb.ToString());
        }
        catch (Exception ex)
        {
            Log.Record(ex);
        }
    }
}
#endregion

#region 记录错误日志

// 记录错误日志
public class Log {

    public static string exceptionFileName;
    
    public static void Record(System.Exception ex) {
        try {
            //清空日志
            if (System.IO.File.Exists(exceptionFileName))
            {
                System.IO.FileInfo myExceptionLogInfo = new System.IO.FileInfo(exceptionFileName);
                if ((myExceptionLogInfo.Length > 100000)) {
                    FileOperate.WriteFile(exceptionFileName, "");
                }
            }
            System.IO.StreamWriter sw = new System.IO.StreamWriter(exceptionFileName, true, System.Text.Encoding.UTF8);
            sw.WriteLine("#######################################");
            sw.WriteLine(("message:" + ex.Message));
            sw.WriteLine(("Source:" + ex.Source));
            sw.WriteLine(("StackTrace:" + ex.StackTrace));
            sw.WriteLine(("DateTime:" + DateTime.Now.ToString()));
            sw.WriteLine("#######################################");
            sw.Close();
        }
        catch {
        }
    }
    
    public static void Record(string message) {
        try {
            System.IO.StreamWriter sw = new System.IO.StreamWriter(exceptionFileName, true, System.Text.Encoding.UTF8);
            sw.WriteLine("#######################################");
            sw.WriteLine(("message:" + message));
            sw.WriteLine(("DateTime:" + DateTime.Now.ToString()));
            sw.WriteLine("#######################################");
            sw.Close();
        }
        catch {
        }
    }
    
    public static void Record(System.Exception ex, string message) {
        try {
            System.IO.StreamWriter sw = new System.IO.StreamWriter(exceptionFileName, true, System.Text.Encoding.UTF8);
            sw.WriteLine("#######################################");
            sw.WriteLine(("message:" + ex.Message));
            sw.WriteLine(("Source:" + ex.Source));
            sw.WriteLine(("StackTrace:" + ex.StackTrace));
            sw.WriteLine(("errorinfo:" + message));
            sw.WriteLine(("DateTime:" + DateTime.Now.ToString()));
            sw.WriteLine("#######################################");
            sw.Close();
        }
        catch {
        }
    }

}
#endregion

#region 读写文件

public class FileOperate
{
    //读文件
    public static string ReadFile(string fileName)
    {
        string fileContent = "";
        try
        {
            System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.StreamReader sr = new System.IO.StreamReader(fs, System.Text.Encoding.UTF8);
            fileContent = sr.ReadToEnd();
            sr.Close();
            fs.Close();
        }
        catch 
        {
        }
        return fileContent;
    }

    //写文件
    public static void WriteFile(string fileName, string wl)
    {
        try
        {
            System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
            System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.UTF8);
            sw.Write(wl);
            sw.Close();
            fs.Close();
        }
        catch 
        {
        }
    }
}

#endregion

#region 操作函数

public class SysCommon {

    //清空窗体    
    public static void clearControl(Control ControlToClear) {
        if ((ControlToClear is System.Web.UI.WebControls.TextBox)) {
            ((System.Web.UI.WebControls.TextBox)(ControlToClear)).Text = "";
        }
        else if ((ControlToClear is System.Web.UI.WebControls.CheckBox)) {
            ((System.Web.UI.WebControls.CheckBox)(ControlToClear)).Checked = false;
        }
        else if ((ControlToClear is System.Web.UI.WebControls.DropDownList)) {
            ((System.Web.UI.WebControls.DropDownList)(ControlToClear)).SelectedIndex = -1;
        }
    }

    public static void SelectNull(System.Web.UI.Page formClass)
    {
        //若未选中任何行，客户端的提示
        string Bkey = "onclick";
        const string Bvalue = "javascript:if(CurrentselectRow==-1){alert(\'请选择相应的数据\');return false;}";
        if (formClass.FindControl("BtnPrint") != null)
        {
            ((Button)(formClass.FindControl("BtnPrint"))).Attributes.Add(Bkey, Bvalue);
        }
        if (formClass.FindControl("BtnModify") != null)
        {
            ((Button)(formClass.FindControl("BtnModify"))).Attributes.Add(Bkey, Bvalue);
        }
        if (formClass.FindControl("BtnDelete") != null)
        {
            ((Button)(formClass.FindControl("BtnDelete"))).Attributes.Add(Bkey, (Bvalue + "else return confirm(\'确实要删除吗？\');"));
        }
    }


    //重置窗体
    public static void ResetForm(System.Web.UI.Page formToReset)
    {
        //重置窗体
        foreach (System.Web.UI.Control objControl in formToReset.Controls) {
            ResetControl(objControl);
        }
    }

    public static void ResetControl(Control ControlToReset)
    {
        clearControl(ControlToReset);
        if ((ControlToReset.Controls.Count > 0)) {
            for (int i = 0; i < ControlToReset.Controls.Count; i++) {
                ResetControl(ControlToReset.Controls[i]);
            }
        }
    }

    public class JavaScript
    {
        //弹出JavaScript小窗口
        public static void alert(string message)
        {
            string js = "<Script language='JavaScript'>alert('" + message.Replace("'", "\"") + "');</Script>";
            HttpContext.Current.Response.Write(js);
        }
    }

    public static bool IsDate(string str)
    {
        bool result = true;
        DateTime date;

        try
        {
            date = Convert.ToDateTime(str);
        }
        catch
        {
            result = false;
        }

        return result;
    }



    //防注入攻击
    public static string ProcessSqlStr(string sqlstr)
    {
        try
        {
            if (sqlstr != null && sqlstr.Length > 0)
            {
                string 注入字符串 = "'|and|exec|insert|select|delete|update|count|*|chr|mid|master|truncate|char|declare";

                string[] anySqlStr = 注入字符串.Split('|');
                foreach (string ss in anySqlStr)
                {
                    if (sqlstr.ToLower().IndexOf(ss) >= 0)
                    {
                        sqlstr = sqlstr.Substring(0, sqlstr.ToLower().IndexOf(ss));
                    }
                }
            }
        }
        catch
        {
        }

        return sqlstr;
    }

    public static string ProcessSqlStr(object sqlstr)
    {
        return ProcessSqlStr(Convert.ToString(sqlstr));
    }

    public static string ProcessSqlStr(int sqlstr)
    {
        return Convert.ToString(sqlstr);
    }



    /// <summary>
    /// 判断输入的校验码是否正确
    /// </summary>
    /// <param name="checkCode"></param>
    /// <returns></returns>
    public static bool CheckCodeSame(string checkCode)
    {
        bool bSame = false;

        if (HttpContext.Current.Session["CheckCode"] != null)
        {
            if (checkCode.ToUpper() == HttpContext.Current.Session["CheckCode"].ToString().ToUpper())
            {
                bSame = true;
            }
        }
        return bSame;
    }
    
    //返回是否已登录
    public static int getUser_id()
    {
        return Convert.ToInt32(HttpContext.Current.Session["user_id"]);
    }
    
    //返回是否已登录
    public static bool isUserLogin()
    {
        if (Convert.ToString(HttpContext.Current.Session["user_id"]).Length == 0 || Convert.ToString(HttpContext.Current.Session["user_name"]).Length == 0)
        {
            return false;
        }
        else
        {
            return true;
        }
    }

    //未登录跳转到登录界面
    public static void checkUserLogin()
    {
        if (Convert.ToString(HttpContext.Current.Session["user_id"]).Length == 0 || Convert.ToString(HttpContext.Current.Session["user_name"]).Length == 0)
        {
            HttpContext.Current.Response.Redirect("~/users/user_login.aspx");
        }
    }

    //得到客户端IP
    public static string getClientIP()
    {
        if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null) // 服务器， using proxy
        {
            //得到真实的客户端地址
            return HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString(); // Return real client IP.
        }
        else//如果没有使用代理服务器或者得不到客户端的ip not using proxy or can't get the Client IP
        {
            //得到服务端的地址
            return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString(); //While it can't get the Client IP, it will return proxy IP.
        }

    }
    
}


public class MyDES {
    
    // DES加密
    public static string sKey = "lgjkkysyymf4core";      //必须是8位的密钥
    
    public static string md5a(string s) {
        // MD5加密
        string strPlainText = s;
        // 用于存放明文字符串的数组
        byte[] hashedDataBytes;
        UTF8Encoding encoder = new UTF8Encoding();
        // ��MD5CryptoService�� 
        MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
        // ��З 
        hashedDataBytes = md5Hasher.ComputeHash(encoder.GetBytes(strPlainText));
        return Convert.ToBase64String(hashedDataBytes);
    }
    
    public static string Encrypt(string Str) {
        Byte[] ByteArrayInput = System.Text.Encoding.Default.GetBytes(Str);
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
        CryptoStream CryptoStream = new CryptoStream(ms, DES.CreateEncryptor(System.Text.Encoding.Default.GetBytes(sKey), System.Text.Encoding.Default.GetBytes(sKey)), CryptoStreamMode.Write);
        CryptoStream.Write(ByteArrayInput, 0, ByteArrayInput.Length);
        CryptoStream.FlushFinalBlock();
        return Convert.ToBase64String(ms.ToArray());
    }
    
    public static string Encrypt2(string Str) {
        //和Encrypt一样的
        Byte[] ByteArrayInput = System.Text.Encoding.Default.GetBytes(Str);
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
        DES.Key = System.Text.Encoding.Default.GetBytes(sKey);
        DES.IV = System.Text.ASCIIEncoding.ASCII.GetBytes(sKey);
        ICryptoTransform desencrypt = DES.CreateEncryptor();
        CryptoStream cryptostream = new CryptoStream(ms, desencrypt, CryptoStreamMode.Write);
        cryptostream.Write(ByteArrayInput, 0, ByteArrayInput.Length);
        cryptostream.FlushFinalBlock();
        return Convert.ToBase64String(ms.ToArray());
    }
    
    public static string Decrypt(string Str) {
        Byte[] ByteArrayInput = Convert.FromBase64String(Str);
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
        CryptoStream CryptoStream = new CryptoStream(ms, DES.CreateDecryptor(System.Text.Encoding.Default.GetBytes(sKey), System.Text.Encoding.Default.GetBytes(sKey)), CryptoStreamMode.Write);
        CryptoStream.Write(ByteArrayInput, 0, ByteArrayInput.Length);
        CryptoStream.FlushFinalBlock();
        return System.Text.Encoding.Default.GetString(ms.ToArray());
    }
}


#endregion
